import React, { Component } from 'react';
import {connect} from 'react-redux'
import {
  Form,
  Input,
  InputNumber,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
  message,
  Modal,
  Popover,
  Spin
} from 'antd';

// 引入自定义的组件
import { DoRegister, DoRegisterSaga, GetCaptchaSaga, DoRegisterValue } from '../../redux/actions/register'
import { DoLogin } from '../../redux/actions/login'
import { ChangeSpinACtivate } from '../../redux/actions/public'
import { API_URL_GO } from '../../env'
const { Option } = Select;

// 类似样式，调节方框的距离
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 6,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};

class RegistrationForm extends Component {

  // const { RegisterState } = this.props

  state = {
    email: '', // 用这个来检测输入邮箱的变化，在点击发送验证码的时候，携带这个参数去请求
    getCaptchaValue: '获取验证码', // 点击后会改变文本框，出现倒计时
    disabled: false,
    register_success: false
  }

  // email 认证错误
  email_error = () => {
    const { RegisterState, DoRegisterValue, DoRegister, DoLogin, ChangeSpinACtivate } = this.props
    message.warning("该邮箱已被注册")
    DoRegisterValue({email_error: false})
    ChangeSpinACtivate({register_activate: false})
  }

  // 验证码错误
  captcha_error = () => {
    const { RegisterState, DoRegisterValue, DoRegister, DoLogin, ChangeSpinACtivate } = this.props
    message.warning("输入验证码错误, 或者验证码已过期")
    DoRegisterValue({captcha_error: false})
    ChangeSpinACtivate({register_activate: false})
  }

  // 注册成功
  register_success = () => {
    const { RegisterState, DoRegisterValue, DoRegister, DoLogin, ChangeSpinACtivate } = this.props
    DoRegisterValue({register_success: false})
    Modal.success({
      title: '注册成功',
      content: (
        <div>
          <p>您的平台账号是: <b style={{color: 'red', display: 'inline'}}>{RegisterState.username}</b></p>
          <p>请您要记住您的平台账号</p>
        </div>
      ),
      onOk() {
        // DoRegisterValue({register_success: false})
        DoRegister({isRegister:false})
        DoLogin({activate: true})
        ChangeSpinACtivate({register_activate: false})
      }
    })
  }

  // 点击提交按钮
  onFinish = (values) => {
    console.log('Received values of form: ', values);
    this.props.DoRegisterSaga(values)
    this.props.ChangeSpinACtivate({register_activate: true})
  };

  // 点击获取验证码按钮
  onGetCaptcha = () => {
    // 验证是否输入的是否是邮箱
    var reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
    if (reg.test(this.state.email)){
      this.props.GetCaptchaSaga(this.state)
      this.setState({
        disabled:true
      })
      message.success("验证码已发送, 请注意查收")
      // 获取验证码成功，则进入倒计时
      var countDown=30;
      // 定时器
      var timer = setInterval(() => {
        if(countDown > 0){
          this.setState({
            getCaptchaValue: countDown+"秒后重新发送"
          })
        }else{
            // 如果不需要倒计时，则清除，否则会一直执行
            clearInterval(timer);
            this.setState({
              getCaptchaValue: "获取验证码",
              disabled: false
            })
        }
        countDown -= 1;
      }, 1000);
    } else{
      message.error("输入邮箱账号再请求验证码")
    }
  }

  handleChangeEmail = (e) => {
    this.setState({
      email: e.target.value
    }) 
  }

  render(){
    const content_for_popover = (
      <div>
        <p>1.在本平台提现, 将会被平台收起1%作为服务费</p>
        <p>2.在本平台提现, 只能整百进行提现</p>
        <p>3.平台协议解释权, 归本平台所有</p>
      </div>
    )
    const { SpinState } = this.props
    console.log("SpinState is ", SpinState)
    const { RegisterState, DoRegisterValue, DoRegister, DoLogin, ChangeSpinACtivate } = this.props
    return (
      <Form
        {...formItemLayout}
        name="register"
        onFinish={this.onFinish}
        scrollToFirstError
      >
        <Form.Item
          name="email"
          label="注册邮箱"
          rules={[
            {
              type: 'email',
              message: '请输入正确的邮箱格式!',
            },
            {
              required: true,
              message: '请输入您的邮箱!',
            },
            {
              max: 100,
              message: '您输入的邮箱过长，请限定在100个字符',
            },
          ]}
        >
          <Input onChange={this.handleChangeEmail} />
        </Form.Item>

        <Form.Item
          name="password"
          label="登录密码"
          rules={[
            {
              required: true,
              message: '请输入您的密码!',
            },
            {
              max: 200,
              message: '您输入的密码过长，请限定在200个字符',
            },
          ]}
          hasFeedback
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="confirm"
          label="确认密码"
          dependencies={['password']}
          hasFeedback
          rules={[
            {
              required: true,
              message: '请再次输入您的密码!',
            },
            {
              max: 200,
              message: '您输入的确认密码过长，请限定在200个字符',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }

                return Promise.reject(new Error('您现在输入的密码和上次输入的密码不相同!'));
              },
            }),
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="nickname"
          label="昵称"
          tooltip="您希望大家怎么称呼您呢？"
          rules={[
            {
              required: true,
              message: '请输入您的昵称!',
              whitespace: true,
            },
            {
              max: 100,
              message: '您输入的昵称过长，请限定在100个字符',
            },
          ]}
        >
          <Input />
        </Form.Item>


        <Form.Item
          name="intro"
          label="自我介绍"
        >
          <Input.TextArea showCount maxLength={200} />
        </Form.Item>

        <Form.Item
          name="gender"
          label="用户性别"
          rules={[
            {
              required: true,
              message: '请输入您的性别!',
            },
          ]}
        >
          <Select placeholder="您的性别">
            <Option value="男">男</Option>
            <Option value="女">女</Option>
            <Option value="其他">其他</Option>
          </Select>
        </Form.Item>

        <Form.Item label="验证码" extra="我们希望是您本人操作!">
          <Row gutter={8}>
            <Col span={12}>
              <Form.Item
                name="captcha"
                noStyle
                rules={[
                  {
                    required: true,
                    message: '请输入您邮箱获取到的验证码!',
                  },
                  {
                    max: 6,
                    message: '您输入的验证码长度过长!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Button onClick={this.onGetCaptcha} disabled={this.state.disabled}>{this.state.getCaptchaValue}</Button>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item
          name="agreement"
          valuePropName="checked"
          rules={[
            {
              validator: (_, value) =>
                value ? Promise.resolve() : Promise.reject(new Error('您还未勾选')),
            },
          ]}
          {...tailFormItemLayout}
        >
          <Checkbox>
            我已阅读,并同意 
            <Popover content={content_for_popover} title='平台协议' trigger='click'>
              <a href="">《平台协议》</a>
            </Popover>
          </Checkbox>
        </Form.Item>
        <Spin spinning={ SpinState.register_activate } tip="注册中......">
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              注册申请
            </Button>
            {
              this.state.email 
              ? 
              <a href={API_URL_GO + "register/get_captcha/" + this.state.email} target="_blank" >&nbsp;收不到验证码</a>
              :
              <></>
            }
          </Form.Item>
        </Spin>
        {
          RegisterState.email_error
          ?
          this.email_error()
          :
          null
        }
        {
          RegisterState.captcha_error
          ?
          this.captcha_error()
          :
          null
        }
        {
          RegisterState.register_success 
          ?
          this.register_success()
          :
          null
            
        }
        
      </Form>
    );
  }
};

export default connect(
  state => ({
    RegisterState: state.RegisterReducer.register,
    SpinState: state.PublicReducer.spinState
  }),
  {
    DoRegisterSaga, // 注册请求
    GetCaptchaSaga, // 获取注册验证码
    DoRegisterValue, // 修改后端返回的注册信息
    DoRegister,
    DoLogin,
    ChangeSpinACtivate, // 共用的加载状态
  }
)(RegistrationForm) 